package com.cfpamf.ms.insur.pay.facade.config;

import com.cfpamf.ms.insur.pay.facade.constant.PayConstant;
import com.cfpamf.ms.insur.pay.facade.util.SignUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

/**
 * 生成公用签名
 * Create By zhengjing on 2019-10-21 14:38
 */
@Slf4j
public class PaySignInterceptor implements RequestInterceptor {

    private static final String HEADER_SIGN = PayConstant.HEADER_NAME_SIGN;

    private String clientKey;

    private String sourceSys;

    private ObjectMapper mapper;

    public PaySignInterceptor(String sourceSys, String clientKey, ObjectMapper mapper) {
        this.sourceSys = sourceSys;
        this.clientKey = clientKey;
        this.mapper = mapper;
    }

    /**
     * Called for every request. Add data using methods on the supplied {@link RequestTemplate}.
     *
     * @param template
     */
    @Override
    @SuppressWarnings("unchecked")
    public void apply(RequestTemplate template) {

        //添加请求来源的系统编码
        template.header(PayConstant.HEADER_NAME_SYS, sourceSys);
        byte[] body = template.body();

        if (!(body == null || body.length == 0)) {
            try {
                Map<String, Object> data = mapper.readValue(body, Map.class);
                template.header(HEADER_SIGN, SignUtil.MD5(data, clientKey));
            } catch (IOException e) {
                throw new IllegalArgumentException("调用facade失败[" + template.url() + "]==>参数不是json格式");
            }
        }
    }
}
